<?php

session_start();

header('Content-Type: text/html; charset=utf-8');

require_once("cfg/def.php");
require_once("cfg/cfg.php");
require_once("lib/utils.func.php");
require_once("lib/err.package.php");
require_once("lib/logger.class.php");
require_once("lib/xtemplate.class.php");
require_once("models/person.class.php");

$eHandler = new exceptionErrorHandler();
$eHandler->error_formatter = new SimpleFormatter();

Logger::$log_file = USR_LOG_FILE;
Logger::Write("new.php GET", print_r($_GET, true));
Logger::Write("new.php POST", print_r($_POST, true));

try
{
    $x = new XTemplate("view/new.xtpl");
    $x->assign("session_name", session_name());
    $x->assign("session_id",   session_id());
    // если была попытка ввода информации
    if(postv("is_ok", "x") == "OK")
    {
        // проверка капчи
        if(isset($_SESSION['captcha']) && $_SESSION['captcha'] == $_POST['key'])
        {
            $err = Person::validate($_POST);
            if($err == "")
            {
                Person::save($_POST["name_f"], $_POST["name_l"], $_POST["name_m"], $_POST["phone"], $_POST["email"]);
                $x->parse("root.reg_ok");
            }
            else
            {
                set_form_data($x);
                $x->assign("img_src", session_name().session_id());
                $x->parse("root.reg_form");
                $x->assign("reg_err", str_replace("\n", "<br/>", $err));
                $x->parse("root.reg_err");
            }
        }
        else
        {
            $x->assign("err_captcha", "Неверный код :(");
            $x->parse("root.reg_form");
        }
        unset($_SESSION['captcha']);
    }
    else
    {
        $x->parse("root.reg_form");
    }
    $x->parse("root");
    $x->out("root");
}
catch(Exception $e)
{
    $x = new XTemplate("view/error.xtpl");
    $x->parse("root");
    $x->out("root");
    
    Logger::Write("new.php", $e);
}


function set_form_data(&$xtpl)
{
    foreach($_POST as $key => $val)
        $xtpl->assign($key, $val);
}
